import { Controller } from 'egg';

class AdvertController extends Controller {

    /**
     * 查询广告列表
     */
    public async searchAdvertList() {
        const { ctx } = this;
        const result = await this.ctx.service.advertService.searchAdvertList(ctx.request.body);
        ctx.body = { code: 1, msg: '查询成功', data: result };
    }

    /**
     * 新增广告
     */
    public async createAdvert() {
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                advert_type: 'type',
                advert_partment: 'string',
            }, request.body)
        } catch (e) {
            ctx.body = this.ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        await this.ctx.service.advertService.createAdvert(request.body);
        ctx.body = { code: 1, msg: '新增成功' };
    }

    /**
     * 修改广告 
     */
    public async updateAdvert() {
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                advert_id: 'string',
            }, request.body)
        } catch (e) {
            ctx.body = this.ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        await this.ctx.service.advertService.updateAdvert(request.body);
        ctx.body = { code: 1, msg: '修改成功' };
    }

    /**
     * 启用、停用广告
     */
    public async startAndStopAdert() {
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                advert_id: 'string',
                type: 'type'
            }, request.body)
        } catch (e) {
            ctx.body = this.ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        const param = ctx.request.body;
        const advert_id = param.advert_id;
        let type = param.type;
        type = String(type);
        await this.ctx.service.advertService.startAndStopAdert(advert_id, type);
        ctx.body = { code: 1, msg: '操作成功' };
    }

    /**
     * 上移、下移广告
     */
    public async removeAdvert() {
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                advert_id: 'string',
                advert_order: 'string',
                type: 'type'
            }, request.body)
        } catch (e) {
            ctx.body = this.ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        const param = ctx.request.body;
        const advert_id = param.advert_id;
        let advert_order = param.advert_order;
        let type = param.type;
        advert_order = Number(advert_order);
        if (typeof (advert_order) !== "number" || isNaN(advert_order)) {
            ctx.body = { code: 4, msg: '序号必须为数字' };
            return;
        }
        type = Number(type);
        await this.ctx.service.advertService.removeAdvert(advert_id, advert_order, type);
        ctx.body = { code: 1, msg: '移动成功' };
    }
}
export default AdvertController;